package com.yuelife.controller;

import com.yuelife.pojo.Helpsendorder;
import com.yuelife.pojo.Workman;
import com.yuelife.service.HelpSendOrderService;
import com.yuelife.service.WorkmanService;
import entity.JwtUtil;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author by Rxzeg
 * @date 2020-07-02 21:13
 * @describe
 */
@Controller
@CrossOrigin
@RequestMapping("/workman")
public class WorkManController {
    @Autowired
    private WorkmanService workmanService;

 /*   @RequestMapping("/login")
    @ResponseBody
    public Map login(){
        Map map=new HashMap<>();
        return  map;
    }*/
    /**
     * 通过账号和密码登录（携带user对象）
     * @param user
     * @return
     */
    @GetMapping("/login")
    @ResponseBody
    public Result loginWithNameAndPwd(Workman user) {
        if (user == null) {
            return new Result(false, StatusCode.ERROR,"登录失败");
        }
        String tel = user.getTelephone();
        String password = user.getPassword();
        System.out.println(tel);
        System.out.println(password);
        try {
            if (StringUtils.isEmpty(tel) || StringUtils.isEmpty(password)) {
                return new Result(false,StatusCode.ERROR,"账号或者密码不能为空");
            }
            if (workmanService.findByName(tel) == null) {
                return new Result(false,StatusCode.ERROR,"用户名或者密码不匹配");
            }
            password=code(password);
            Workman findByNameAndPassword = workmanService.findByNameAndPassword(tel,password);
            if (findByNameAndPassword == null) {
                return new Result(false,StatusCode.ERROR,"用户名或者密码不正确");
            } else {
                //Workman byName = workmanService.findByName(tel);
                String token= JwtUtil.createJwt(findByNameAndPassword.getId()+"",findByNameAndPassword.getUsername());
                return new Result(true,StatusCode.OK,"登录成功",token);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,StatusCode.ERROR,e.getMessage());
        }
    }
    /**
     * md5加密方法
     * @param str
     * @return
     */
    private static String code(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[] byteDigest = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < byteDigest.length; offset++) {
                i = byteDigest[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            //32位加密
            return buf.toString();
            // 16位的加密
            //return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }
    @PostMapping("/profile")
    @ResponseBody
    public Map profile(HttpServletRequest request){
        Map map=new HashMap<>();
        try {
            //从请求头获取token数据
            String authorization = request.getHeader("Authorization");
            if(StringUtils.isEmpty(authorization)){
                throw new Exception();
            }
            String token = authorization.replace("Bearer", "");
            //解析token
            Claims claims = JwtUtil.parseJwt(token);
            String id = (String) claims.get("id");
            System.out.println("token"+id);
           Workman byId= workmanService.findByid(Integer.valueOf(id));
            System.out.println(byId.toString());
            map.put("byId",byId);
                map.put("code",200);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
           /* return new Result(true,StatusCode.ERROR,"加载失败");*/
            return map;
        }
    }
    @Autowired
    private HelpSendOrderService helpSendOrderService;
    @GetMapping("/getorder")
    @ResponseBody
    public  Map getsendorder(Integer workmanid){
        Map map=new HashMap<>();
        System.out.println("getorder1111");
        System.out.println(workmanid);
        List<Helpsendorder>  helpsendorders=helpSendOrderService.getAllOrder();
        System.out.println(helpsendorders.toString());
        map.put("helpsendorders",helpsendorders);
        return map;
    }
}
